﻿using System.Configuration;
using System.Data.Common;
using System.Data.OleDb;
using System.Data.SqlClient;

namespace CustonFramework.Config
{
    public class DbConfig : ConfigurationSection
    {
        [ConfigurationProperty("dbConfig", IsDefaultCollection = true)]
        public DbConfigCollection DbConfigs => this["dbConfig"] as DbConfigCollection;
    }
    public class DbConfigCollection : ConfigurationElementCollection
    {

        protected override ConfigurationElement CreateNewElement()
        {
            return new DbConfigElement();
        }

        /// <summary>
        /// 获取元素key值，不存在则返回null
        /// </summary>
        /// <param name="element"></param>
        /// <returns></returns>
        protected override object GetElementKey(ConfigurationElement element)
        {
            return ((DbConfigElement) element)?.Name;
        }
        public ConfigurationElement this[object key]
        {
            get => (DbConfigElement)BaseGet(key);
            set
            {
                if (BaseGet(key) != null)
                {
                    BaseRemove(key);
                }

                BaseAdd(value);
            }
        }

        /// <summary>
        /// 默认配置
        /// </summary>
        [ConfigurationProperty("defaultConfig", IsRequired = true, DefaultValue = "default")]
        public string DefaultConfig
        {
            get => base["defaultConfig"] as string;
            set => base["defaultConfig"] = value;
        }
    }
    public class DbConfigElement : ConfigurationElement
    {
        /// <summary>
        /// 配置名称
        /// </summary>
        [ConfigurationProperty("name", IsRequired = true)]
        public string Name => this["name"] as string;

        /// <summary>
        /// sqlserver,oracle
        /// </summary>
        [ConfigurationProperty("dbType", IsRequired = true)]
        public string DbType => this["dbType"] as string;

        [ConfigurationProperty("connectionString", IsRequired = true)]
        public string ConnectionString => this["connectionString"] as string;

        public DbConnection GetDbConnection()
        {
            switch (DbType)
            {
                default:
                    return new SqlConnection(ConnectionString);
                case "oracle":
                    return new OleDbConnection(ConnectionString);
            }
        }
    }
}